#! /usr/bin/perl -w

use strict;
use warnings;

use Data::Dumper;
use JSON::XS;
use IO::Socket;
use Sys::Hostname;
use constant BUFSIZE => 1024;

my $JSONObject = JSON::XS->new->ascii->pretty->allow_nonref();

my $host   = hostname;
my $port   = shift || '10280';
my $socket = new IO::Socket(
  Domain    => PF_INET,
  Proto     => getprotobyname('tcp'),
  LocalAddr => $host,
  LocalPort => $port,
  Listen    => 1,                       #SOMAXCONN,
                                        #ReuseAddr => SO_REUSEADDR,
) or die $@;
my $buffer;

print "Waiting to do service...\n";
while (my $client = $socket->accept) {
  print "Client: ", $client->peerhost, " Connected..\n";
  syswrite($client, "Reached Server\n", BUFSIZE);
  if (sysread($client, $buffer, BUFSIZE) > 0) {
    my @AoH = $JSONObject->decode($buffer);
    print "AoH: " . Dumper(@AoH);
  }
}
